﻿using System;
using System.Data.SQLite;

namespace StudentManagementSystem.Repositories
{
    public abstract class BaseRepository
    {
        protected readonly DB.DBContext _dbContext;

        public BaseRepository(DB.DBContext dbContext)
        {
            _dbContext = dbContext;
        }

        protected void LogAction(string action, string tableName, string recordId = null, string details = null)
        {
            try
            {
                using (var connection = _dbContext.GetConnection())
                {
                    connection.Open();
                    using (var command = new SQLiteCommand(connection))
                    {
                        command.CommandText = @"
                            INSERT INTO Logs (Action, TableName, RecordId, Details, CreatedAt)
                            VALUES (@Action, @TableName, @RecordId, @Details, @CreatedAt)";
                        command.Parameters.AddWithValue("@Action", action);
                        command.Parameters.AddWithValue("@TableName", tableName);
                        command.Parameters.AddWithValue("@RecordId", recordId != null ? (object)recordId : DBNull.Value);
                        command.Parameters.AddWithValue("@Details", details != null ? (object)details : DBNull.Value);
                        command.Parameters.AddWithValue("@CreatedAt", DateTime.Now);
                        command.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"日志记录失败: {ex.Message}");
            }
        }
    }
}